from django.db.models import QuerySet
from django.http import HttpResponse, QueryDict
from django.views import View
import article.models as models
from django.shortcuts import render


class ManageCategoryView(View):
    def get(self,request):
        user_id = request.session.get('user_id','')
        article_category = models.ArticleCategory.objects.all().filter(create_user_id=user_id)
        return render(request,'manage/category/category_home.html',locals())
    def post(self,request):
        param:QueryDict
        param = request.POST
        category_name = param.get('category_name',"")
        user_id = request.session.get('user_id', '')
        article_category = models.ArticleCategory.objects.all().filter(create_user_id=user_id)
        if category_name:
            article_category = article_category.filter(category_name=category_name)
        return render(request, 'manage/category/category_home.html', locals())


class ManageAddCategoryView(View):
    def get(self,request):
        return render(request,'manage/category/category_add.html')
    def post(self,request):
        param:QueryDict
        param = request.POST
        user_id = request.session.get('user_id','')
        article_category = models.ArticleCategory.objects.all().filter(create_user_id=user_id)
        category_name = param.get('category_name',"")
        for category in article_category:
            if category_name == category.category_name:
                return HttpResponse("类别已存在，<a href='/manage/category/'>点击返回类别管理</a>")
        if category_name:
            models.ArticleCategory(category_name=category_name).save()
            return HttpResponse("添加成功，<a href='/manage/category/'>点击返回类别管理</a>")
        return HttpResponse("添加失败，<a href='/manage/category/'>点击返回类别管理</a>")


class ManageUpdateCategoryView(View):
    def get(self,request,id):
        article_category = models.ArticleCategory.objects.get(id=id)
        return render(request,'manage/category/category_update.html',locals())
    def post(self,request,id):
        param:QueryDict
        param = request.POST
        user_id = request.session.get('user_id','')
        article_category = models.ArticleCategory.objects.all().filter(create_user_id=user_id)
        category_name = param.get('category_name',"")
        for category in article_category:
            if category_name == category.category_name:
                return HttpResponse("类别已存在，<a href='/manage/category/'>点击返回类别管理</a>")
        if category_name:
            models.ArticleCategory.objects.filter(id=id).update(category_name=category_name)
            return HttpResponse("修改成功，<a href='/manage/category/'>点击返回类别管理</a>")
        return HttpResponse("修改失败，<a href='/manage/category/'>点击返回类别管理</a>")


class ManageDelCategoryView(View):
    def get(self,request,id):
        models.ArticleCategory.objects.filter(id=id).delete()
        return HttpResponse("删除成功，<a href='/manage/category/'>点击返回类别管理</a>")